//
//  AppDelegate.m
//  DiZhenYuJing
//
//  Created by zhibao on 2024/1/31.
//

#import "AppDelegate.h"
#import "LNavigationViewController.h"
#import <StoreKit/StoreKit.h>
#import "TabBarController.h"
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<SKPaymentTransactionObserver,JPUSHRegisterDelegate>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2025-08-25 20:00:00"]) {
        [MYGlobal share].shenHeFlag = 1;
    }
    [UMConfigure initWithAppkey:@"670547ee80464b33f6d6f64c" channel:@"APP Store"];
    [MobClick setAutoPageEnabled:YES];
    
    
    //【初始化sdk】
    [JPUSHService setupWithOption:launchOptions appKey:@"3c5755860dd89bbbf5c5953d"
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    //【注册通知】通知回调代理（可选）
     JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
     entity.types =  JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
     [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService setBadge:0];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    
    /*
     * 初始化
     */

    
    //导航
    [self setNavConfig];
    //初始化
    [self setTabbarController];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
    //sdk注册DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return NO;
}

- (void)setTabbarController {
    
    NSString *tempFirstStr = [[NSUserDefaults standardUserDefaults] valueForKey:WelcomeFlag];
    MYAPP.window.rootViewController = [UIViewController new];
    DLog(@"eeeee===%@",[MYGlobal share].vip_expiry);
    
    if ([MYGlobal share].shenHeFlag == 1) {
        TabBarController *tabController = [TabBarController new];
        self.window.rootViewController = tabController;
    }else{
        if (tempFirstStr.length > 4) {
            TabBarController *tabController = [TabBarController new];
            self.window.rootViewController = tabController;
        }else{
            MYAPP.window.rootViewController = [WelcomeController new];
        }
    }
    
}

- (void)setNavConfig {
    // 配置导航栏属性
    [GKConfigure setupCustomConfigure:^(GKNavigationBarConfigure *configure) {
        //       configure.gk_translationX = 15;
        //       configure.gk_translationY = 20;
        configure.backgroundColor = MyColor(@"#000000");
        configure.titleFont = MY_SCALE_RegularFONT(18);
        configure.titleColor = MyColor(@"#000000");
        //       configure.gk_scaleX = 0.90;
        configure.backImage = [UIImage imageNamed:@"arrow_back"];
        //       configure.gk_scaleY = 0.92;
        configure.gk_navItemLeftSpace = 12.0f;
        configure.gk_navItemRightSpace = 12.0f;
    }];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = YES;
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0); {
    
    return YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return YES;
}


#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    DLog(@"程序将要进入前台");
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
//    [[MYGlobal share].player play];
}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
   
    if(transactions.count > 0){
        SKPaymentTransaction *tran = transactions.lastObject;
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                [self verifyPurchaseWithPaymentTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                [DWKeychainTool saveItem:@"" key:@"id"];
                break;
            default:
                break;
        }
    }
}
- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    //交易验证
    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    if(!receipt){
        return;
    }
    NSString *idkey = [DWKeychainTool getItemForKey:@"id"];
    NSString *time = [Helper getTime:TimeTypeZhou];
    if([idkey isEqualToString:@"comg.yuliang.paipan.yue"]){
        time = [Helper getTime:TimeTypeYue];
    }else if([idkey isEqualToString:@"comg.yuliang.paipan.ji"]){
        time = [Helper getTime:TimeTypeJi];
    }else if([idkey isEqualToString:@"comg.yuliang.paipan.nian"]){
        time = [Helper getTime:TimeTypeNian];
    }else if([idkey isEqualToString:@"com.yasuo.yongjiu"]){
        time = [Helper getTime:TimeTypeYongJiu];
    }
//    MobClick.event("dingyue", attributes: ["type":"购买","id":payID,"quantity":IAPShare.sharedHelper().iap.getLocalePrice(product) ?? "0"])
    [MobClick event:@"dingyue" attributes:@{@"type":@"xuding", @"id":transaction.payment.productIdentifier}];
    [MYGlobal share].vip_expiry = time;
}

# pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
  if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //从通知界面直接进入应用
  }else{
    //从通知设置界面进入应用
  }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
    completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler();    // 系统要求执行这个方法
    DLog(@"didReceiveNotificationResponse");
}

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(nullable NSDictionary *)info { 
    DLog(@"info==%@",info);
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [JPUSHService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
    DLog(@"didReceiveRemoteNotification");
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
    DLog(@"didReceiveRemoteNotification111");
}

@end
